package com.cn.shiro.demo.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.cn.shiro.demo.pojo.User;
import com.cn.shiro.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import javax.annotation.Resource;
/**
 * 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 给予当前用户权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        // 根据数据库字段添加用户的权限 user:add
        simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());
        return simpleAuthorizationInfo;
    }
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        // 条件构造器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",token1.getUsername());
        User user = userService.getOne(wrapper);
        if(user==null){
            return null; // 未知用户名 异常
        }
        // 获得当前用户
        Subject subject = SecurityUtils.getSubject();
        // 登录成功把用户存到session
        Session session = subject.getSession();
        session.setAttribute("currentUser",user);
        // 密码认证shrio 做加密
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
    }
}
